Skip to content

Use the new comprehension scoping in every function (#919 follow-up) - #924

Merged
craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:comprehension-scope-every-function
Nov 23, 2026
Merged

craigbarratt merged 2 commits into
custom-components:masterfrom
HoneyBearTech:comprehension-scope-every-function

Conversation

@HoneyBearTech

@HoneyBearTech HoneyBearTech commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

This is the follow-up @craigbarratt suggested on #919: "the new comprehension scoping only applies in functions with an inner function or lambda, so the same code can behave differently depending on that. It would be good to use it in every function eventually." With this PR, every function uses it.

What was different
Since #919, a generator expression used by a comprehension behaved as in Python only in a function that has an inner function, class or lambda. In any other function it saw the comprehension's loop variables instead of the variables where it was made, so a := in it was lost, or it read the wrong value. Adding an inner function, or a lambda that reads a variable, to the function changed the result, even if it was never called:

def f():
    x = 0
    g = ((x := x + 1) for _ in range(3))
    r = [x for x in g]
    return r, x          # before: ([1, 2, 3], 0)   Python and with an inner lambda: ([1, 2, 3], 3)

def f():
    g = ((x := i) for i in range(3))
    r = [x for x in g]
    return x             # before: NameError         Python and with an inner lambda: 2

def f():
    x = 0
    g = ((x := x + 1) for _ in range(3))
    return [next(g) + x for x in range(10, 12)]    # before: [22, 24]   Python: [11, 13]

These are three of the five examples from my reply on #919. All five now match Python in any function.

Why

  • Since Let lambdas use the enclosing function's variables (#725) #919, a function with an inner function, class or lambda keeps each of its local variables in an EvalLocalVar that holds a Python cell, so an inner function or a lambda can share it. EvalFunc.has_closure marked those functions, and check_for_closure() set it.
  • The comprehension and generator expression handling from Let lambdas use the enclosing function's variables (#725) #919 relies on those shared variables: a generator expression keeps the bindings of the function's variables, and a comprehension that reuses a name gets a new local for it, so both see the right variable. It was only turned on where has_closure was true (shares_locals()).
  • In other functions, the variables were plain values in the symbol table, and comprehensions and generator expressions used the old handling, where they share the function's own entries.

What I changed

  • Every function now keeps its local variables in EvalLocalVars: EvalFunc.call() makes one for each of the function's own variables on every call, as it did before only in functions with an inner function. has_closure and check_for_closure() are removed, since nothing else used them.
  • shares_locals() keeps its test that a pyscript function is running (self.in_local_scope() and self.curr_func is not None) and only drops the has_closure part. Code run by eval() and exec() has no running function and keeps a plain dictionary of variables, so it's unchanged. Turning the new handling on there would break a case that works today: with separate locals, exec('g = ((x := x + 1) for _ in range(3)); r = [x for x in g]', {'x': 0}, ns) would give r == [1, 1, 1] instead of Python's [1, 2, 3].
  • As in Python, reading a local variable before it has a value now raises UnboundLocalError ("local variable 'x' referenced before assignment") in every function, not only in one with an inner function. Before, it was NameError ("name 'x' is not defined"), or, for a local that hides a built-in, the built-in itself: n = len("ab") followed later by len = 5 gave 2 instead of raising. UnboundLocalError is a subclass of NameError, so code that catches NameError still works.
  • In a generator expression (its element, conditions and inner iterables), the function's variables are free variables, as in Python. So reading one that has no value there (deleted, or not assigned yet when the generator is advanced) raises NameError, not UnboundLocalError. The generator expression's own loop variables are local to it, so reading one before it's assigned ((x for _ in [0] for x in x)) still raises UnboundLocalError. A list comprehension's loop variables are local to the function or generator expression it runs in, as in Python 3.12 and later. To tell these apart, the new loop variables that comprehensions and generator expressions get are an EvalLoopVar, a small subclass of EvalLocalVar that remembers which generator expression they belong to, or None outside one. Each generator expression gets its own identity object (genexp_id), kept with the rest of its scope next to genexp_iter and set while its element, conditions and inner iterables run; genexp_iter itself can't be used, since two generator expressions can share one iterator. ast_name() raises UnboundLocalError for an empty EvalLoopVar only when that generator expression is the one running, and for an empty function variable only when no generator expression is running (a function called from one resets genexp_id, as it does genexp_iter). This was already wrong on master in some of these cases, in both kinds of function. Lambdas and inner functions that read an empty variable of the function already raised NameError, as in Python.
  • A comprehension's loop variables are no longer counted as the enclosing function's own variables when its names are collected (get_names_set()), unless the function also binds them itself. As in Python, they belong to the comprehension, which already gives them their own variables while it runs. Since every function now has a variable for each of its own names, leaving them counted would have made len unbound after (or before) [len for len in range(2)], instead of finding the built-in. It also fixes a case that was already wrong on master in every function: with a module-level x, reading x in a function after [x for x in range(2)] raised UnboundLocalError instead of reading the global.
  • ast_annassign() now also works when the function has its own __annotations__ variable (__annotations__ = {} or __annotations__: dict = {}), which is now an EvalLocalVar too: it adds the annotation to that variable's dictionary. Before, this only failed in functions with an inner function.
  • Every function call now makes one EvalLocalVar per local variable, and every read or write goes through it. To keep that cost low, without changing behaviour:
    • EvalLocalVar has __slots__, and takes its value as an optional positional argument instead of a **kwargs dictionary;
    • ast_name() reads an EvalLocalVar's cell once. Before, it checked that the variable had a value and then read it again with get(). It only checks for an unbound local when the cell is empty, and raises the same errors as before;
    • EvalFunc.call() no longer checks whether the function's own variables have a value. resolve_nonlocals() used to keep an empty EvalLocalVar for each of them, and call() tested it with is_defined(), which raises and catches a ValueError on an empty cell. Raising an exception costs more the deeper the chain of running coroutines, so with every function using EvalLocalVars, deep recursion would have got much slower (on master this already happens in functions with an inner function). They're now marked with None, and each call makes a new EvalLocalVar for them as before; only variables shared from an enclosing function are tested.
  • A couple of comments that described "a function that shares its variables" now just say "a function".
  • Size: eval.py gets 61 new lines and loses 46. 44 of the new lines are code, and the rest are 4 docstrings, 8 comment lines and 5 blank lines.

Testing

  • test_comprehension_scopes_match_python and test_genexp_walrus_scopes_match_python now run every script both as written, in a function without an inner function, and with with_inner_function(), so both kinds of function are covered. Since the two kinds no longer differ, I merged SHARED_COMPREHENSION_SCOPE_TESTS into COMPREHENSION_SCOPE_TESTS. The first test now runs 36 scripts (18 twice) and the second 30 (15 twice), each compared with CPython.

  • New test_function_locals_match_python runs 23 scripts, each as written and with with_inner_function() (46 in all), and compares them with CPython:

    • the 5 examples from my reply on Let lambdas use the enclosing function's variables (#725) #919. The fifth raises ZeroDivisionError in Python, so the script catches it and returns it with x;
    • reading a local variable before it has a value, and reading a local that hides len before it's assigned. Both give UnboundLocalError, as in Python;
    • reading the function's variable from a generator expression after del x, and before it's assigned from a generator expression's element, condition and inner iterable. These give NameError. Also a lambda and an inner function reading it after del x (NameError), and a list comprehension (UnboundLocalError);
    • a generator expression's own loop variable read before it's assigned, in an inner iterable and in a condition, a list comprehension's in a generator expression, and an inner generator expression's own one (UnboundLocalError); and an outer generator expression's or a list comprehension's loop variable read by an inner generator expression before it's assigned (NameError), also when the inner one uses the outer one's iterator;
    • len called before and after a list, set and dict comprehension and a generator expression whose loop variable is len (4 scripts), and a module-level x read in a function after all four kinds use x as their loop variable;
    • a function's own __annotations__, set with __annotations__ = {} before x: int = 1, and with __annotations__: dict = {};
    • the exec() case above, in a function and at module level, which checks that code run by exec() keeps its old handling;
    • a function called from a generator expression: your script from the review, where the function reads its own local before it has a value (UnboundLocalError, and NameError if call() doesn't reset genexp_id); a method that calls a zero-argument super() when called from one; and an element that calls a function and then reads a variable with no value yet, or uses super(), which must see the same scope after the call.
  • test_eval_exceptions: the case where an inner function reads a variable that its own later del x makes local now expects Python's UnboundLocalError, with the same position.

  • On master, 22 of the 27 scripts that only matched Python in a function with an inner function fail when run in one without: 6 of the 7 former SHARED_COMPREHENSION_SCOPE_TESTS, 11 of the 15 GENEXP_WALRUS_SCOPE_TESTS, and all 5 reply examples. The other 5 already passed and stay as checks: one goes through eval(), three already have their own lambda or inner function, and one uses a global name. The two UnboundLocalError scripts fail on master too, and so does the module-level x script, in both kinds of function. The len scripts for list, set and dict comprehensions, both __annotations__ scripts and the two generator expression NameError scripts pass on master as written, but fail there with an inner function. The loop variable script fails on master in both kinds of function; the one where the inner generator expression uses the outer one's iterator passes there, and checks that this stays as it is. The exec() script passes on master, as it should; it fails if shares_locals() drops its running-function test. All four changed or new tests fail on master.

  • I also checked, on master and with this PR, that locals(), eval() and exec() in a function, recursion, global with del, a decorator closure with nonlocal, super(), a @pyscript_compile inner function, a @pyscript_executor function, tasks made from a generator expression, and releasing a function's variables after it returns (and after a returned generator is closed) give the same results as before. Module-level and class-body cases are unchanged too.

  • Speed. Each workload is a pyscript function f(n), run in one process with master's eval.py and the other versions loaded side by side. Each version gets one warm-up call, then 20 timed calls per workload (10 for the last four rows), alternating the order. I ran that in 3 separate processes (with different hash seeds, since the results move a little from one process to the next), on an otherwise idle machine. The numbers are changes in the median process CPU time against master on Python 3.14, as the range over the 3 processes:

    workload master this PR narrower rule (below)
    arithmetic loop on locals (12,000 iterations) 287 ms -0.6% to +2.0% -1.0% to +1.1%
    local reads and writes (12,000 iterations) 271 ms +0.6% to +1.5% -1.5% to +0.1%
    calls to a small function (10,000 calls) 319 ms +6.5% to +8.8% -1.2% to +1.7%
    a comprehension (18,000 elements) 168 ms -1.3% to +1.8% -1.9% to +0.2%
    recursion, 300 levels, 1 local 12.3 ms +8.7% to +10.9% +2.1% to +5.9%
    recursion, 900 levels, 1 local 37.4 ms +2.7% to +7.8% -1.0% to +0.9%
    recursion, 300 levels, 10 locals 32.7 ms +7.8% to +12.1% -1.1% to -0.4%
    recursion, 900 levels, 10 locals 105 ms +9.8% to +13.6% -1.6% to +2.1%
    the same with an inner function, 300 levels, 1 local 47.6 ms -43.3% to -41.0%
    the same with an inner function, 900 levels, 1 local 269 ms -68.9% to -67.8%
    the same with an inner function, 300 levels, 10 locals 128 ms -60.1% to -59.4%
    the same with an inner function, 900 levels, 10 locals 1,073 ms -85.1% to -83.7%

    The recursion workloads are def r(n) with 1 or 10 local variables besides n, which calls r(n - 1) until n is 0, and in the last four rows also defines an inner function. So most of their time is function calls, and each call now makes an EvalLocalVar for every local variable. That's why deep recursion in a function with 10 local variables is the slowest case: up to about 14% slower than master in these runs. Calls to a small function are up to about 9% slower, and the other workloads are within about 2%.

    Functions with an inner function or lambda, which already used EvalLocalVars on master, got much faster in deep recursion: 1.7 to 6.7 times as fast in the last four rows, because call() no longer tests each of their empty variables by raising and catching an exception. The gain grows with depth and the number of variables; a separate check at 900 and 1,900 levels with up to 50 local variables measured 3 to 17 times as fast.

    Without the first two speed-ups above, an earlier version of this change measured the same way was +4.4% to +5.3%, +8.1% to +11.5%, +13.8% to +17.3% and +3.9% to +6.7% on the first four workloads; most of that came from reading each variable twice. In the runs above, keeping the is_defined() test of the function's own empty variables in call() made the first four recursion workloads +87% to +93%, +231% to +248%, +209% to +223% and +722% to +766%.

    I also measured a narrower alternative, in case you'd prefer it: keep the old inner-function-or-lambda test and also share the variables of every function that contains a generator expression. It's in the last column, with the same speed-ups; these functions have no generator expression, so they don't share their variables and cost about the same as on master (one recursion row was up to about 6% slower). It fixes the same 27 scripts, but not the two UnboundLocalError cases, and it keeps a rule about which functions are special, which is what this PR removes. Since every function costs at most about 9% more on the first four workloads, and up to about 14% on deep recursion with many local variables, I went with every function.

  • The full test suite (335 tests), ruff, ruff format, codespell, pylint, mypy and sphinx-build -W pass on Python 3.14.

Docs
In Language Limitations, the item about generator expressions ended with "unless it was made in a function that has an inner function or lambda". It now says that the difference (a generator expression used by a comprehension sees the comprehension's loop variables) remains only at module level and in class bodies.

Note
Left as it is:

  • At module level and in class bodies, a generator expression used by a comprehension still sees the comprehension's loop variables instead of the variables where it was made. For example, with x = 7 at module level, a class body with g = (x + 1 for _ in range(3)) and r = [x for x in g] gives [8, 9, 10], where Python gives [8, 8, 8]. Your suggestion was about functions, so I've kept these out of this PR.
  • Code run by eval() and exec() keeps its old handling too, as explained above.

These differences from Python were already there before this PR (master gives the same results), and it doesn't change them:

  • A generator expression made in another one's element and used after the outer one has finished reads the enclosing function's variable instead of the outer generator expression's loop variable (this is already in Language Limitations). For example, in def f() with x = 7, inner = list((x for _ in range(2)) for x in range(3)) followed by [list(g) for g in inner] gives [[7, 7], [7, 7], [7, 7]], where Python gives [[2, 2], [2, 2], [2, 2]].
  • In a function that declares global x, a comprehension with the loop variable x overwrites the global x (also in Language Limitations). With x = 0 at module level, [x for x in range(3)] in such a function leaves the global x at 2, where Python leaves it at 0.
  • A := that rebinds a comprehension's loop variable is accepted: [(x := 1) for x in range(3)] gives [1, 1, 1], where Python raises SyntaxError: assignment expression cannot rebind comprehension iteration variable 'x'.

This PR is two commits on current master (933e177): the change, and a second commit with the tests you asked for in your review.

Since custom-components#919, only a function with an inner function, class or lambda
kept its variables in shared cells, and only there did a generator
expression used by a comprehension see the variables where it was made,
as in Python. In other functions it saw the comprehension's loop
variables instead, so the same code gave different results depending on
whether the function had a lambda; for example, a := in the generator
expression was lost.

Every function now keeps its local variables in cells, so every
function handles comprehensions and generator expressions the same way,
and has_closure and check_for_closure() are gone. Code run by eval()
and exec(), module level and class bodies are unchanged. As in Python,
reading a local variable before it has a value now raises
UnboundLocalError in every function, including one that hides a
built-in such as len. In a generator expression, the function's
variables and an enclosing generator expression's loop variables are
free variables, so reading one that has no value there raises
NameError, as in Python, while reading one of its own loop variables
before it's assigned still raises UnboundLocalError.

A comprehension's loop variables are no longer counted as the
enclosing function's own variables, unless the function binds them
itself, so a comprehension over len doesn't hide the built-in, and one
over a global's name no longer makes a later read of the global raise
UnboundLocalError. Annotations also work when a function has its own
__annotations__ variable.

To keep the cost low, EvalLocalVar uses __slots__ and takes its value
as an optional positional argument, reading a local variable checks its
cell once instead of twice, and a call no longer tests an empty
variable for each of the function's own variables, which raised and
caught an exception each time and made deep recursion slow.

The comprehension and generator expression scripts compared with
CPython now also run in functions without an inner function. New ones
cover the examples from custom-components#919, reading a local variable before it has a
value, directly, from a generator expression or as a generator
expression's own loop variable, comprehensions whose loop variable has
the name of a built-in or global, a function's own __annotations__,
and exec() with separate locals.

Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @HoneyBearTech, this is a nice result: one rule for every function, and functions with an inner function or lambda get much faster in deep recursion.

I compared about 25 more scripts with CPython, each as written and with an inner function: arguments and defaults, except ... as e unbinding, del, for/with/import targets, locals(), recursion, global, nonlocal, a local hiding print, comprehension variables not leaking, lambdas in comprehensions, nested comprehensions, :=, inner classes and functions. All of them match. I also timed small calls, a local loop, and recursion with 10 locals with and without an inner function at realistic depths, and got within noise of master (the inner-function case a few percent faster).

One small request. Every mutation I tried was caught by the tests except one: if EvalFunc.call() doesn't reset genexp_id, nothing fails. This script catches it (it gives NameError instead of UnboundLocalError), so it would be worth adding to FUNCTION_LOCALS_TESTS:

def h():
    try:
        y = z
        z = 1
    except NameError as e:
        return type(e).__name__
def f():
    return list(h() for _ in range(1))
result = f()

Add three scripts to FUNCTION_LOCALS_TESTS, each compared with CPython as
written and with an inner function:

- a function called from a generator expression reads its own local before
  it has a value, and gets UnboundLocalError (fails if call() doesn't reset
  genexp_id);
- a zero-argument super() in a method called from a generator expression
  uses the method's own first argument (fails if call() doesn't reset
  genexp_iter);
- a call in a generator expression's element doesn't change what the rest of
  the element sees: a free variable with no value gives NameError, and
  super() still uses the iterator (fail if call() doesn't restore genexp_id
  or genexp_iter).

Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

Thanks @craigbarratt, and thank you for the roughly 25 extra comparisons and the timings. It's good to know that arguments and defaults, except ... as e, del, for/with/import targets, locals(), recursion, global, nonlocal, a local hiding print, :=, nested comprehensions and inner classes and functions all matched CPython, and that the speed is within noise of master.

What I added. I pushed one new commit on top of the existing one, test that a function called from a generator expression resets genexp_id. It only changes tests/test_unit_eval.py; eval.py is untouched. It adds your script, as you wrote it, to FUNCTION_LOCALS_TESTS, with a short comment like the neighbouring entries. test_function_locals_match_python runs every script in that list as written and with with_inner_function(), and compares each with CPython. It had 20 scripts (40 runs) and now has 23 (46 runs): your script plus two more, described below.

Your script fails with the reset removed. I took the genexp_id reset out of EvalFunc.call() (so genexp_iter is still reset) and ran the test. Your script failed both as written and with an inner function. h() gives NameError where CPython gives UnboundLocalError, which is the result you described. With the reset back, it matches CPython in both kinds of function.

The other resets. I did the same for each of the other steps in that part of call(), one at a time, and ran the new script, and the rest of tests/test_unit_eval.py, against each:

  • Without the genexp_iter reset: nothing failed in the new test, and in the full file the run didn't finish (it hung), so it was caught only by accident.
  • Without the restore of either value, without the restore of genexp_iter, and without the restore of genexp_id: the whole file still passed, so none of these was caught.

So I added two small scripts, each checked against CPython and run in both kinds of function:

  • A function called from a generator expression's element that is followed, in the same element, by a read of a variable of the enclosing function that has no value yet. In Python that is a free variable, so it gives NameError. It needs the restore of genexp_id.
  • A method that uses a zero-argument super(), called from a generator expression, and a generator expression in a method whose element calls a method and then uses super() (which gives TypeError in Python, because it passes the iterator). The first part needs the genexp_iter reset, and the second the restore of genexp_iter.

With these, every removal I tried makes at least one script fail, in both kinds of function: the genexp_id reset (your script), the genexp_iter reset and its restore (the super() script), the genexp_id restore (the free variable script), and the restore of both (both of mine).

The full suite (335 tests) and the pre-commit checks pass. Thanks again for catching this.

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @HoneyBearTech, the new tests catch every reset and restore. Approving.

@craigbarratt
craigbarratt merged commit 148e2d3 into custom-components:master Nov 23, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants